package com.quectel.core.module.village.service.impl;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.quectel.constant.global.SystemConstants;
import com.quectel.core.constants.RedisCacheConstants;
import com.quectel.core.module.village.dao.VillageFloorDao;
import com.quectel.core.module.village.dto.VillageBuildingDto;
import com.quectel.core.module.village.dto.VillageFloorDto;
import com.quectel.core.module.village.entity.VillageFloorEntity;
import com.quectel.core.module.village.service.VillageBuildingService;
import com.quectel.core.module.village.service.VillageFloorService;
import com.quectel.core.module.village.service.VillageRoomService;
import com.quectel.util.common.CopyUtils;
import com.quectel.util.kit.CacheKit;
import com.quectel.util.kit.Snowflake;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;

/**
 * @author caolu
 * @email louis.cao@quectel.com
 * @date 2021-10-18 14:41:34
 */
@DubboService
public class VillageFloorServiceImpl implements VillageFloorService {

    private static final Logger LOGGER = LoggerFactory.getLogger(VillageFloorServiceImpl.class);

    @Autowired
    private VillageFloorDao villageFloorDao;
    @Autowired
    private VillageBuildingService villageBuildingService;
    @Autowired
    private VillageRoomService villageRoomService;

    private static final String VILLAGE_FLOOR_CACHE_BY_ID = RedisCacheConstants.PROJECT_NAME + "VILLAGE_FLOOR_CACHE_BY_ID:";

    @Override
    public VillageFloorDto selectByFloorNo(Long buildingId, Integer floorNo) {
        VillageFloorEntity entity = villageFloorDao.selectOne(new LambdaQueryWrapper<VillageFloorEntity>()
                .eq(VillageFloorEntity::getBuildingId, buildingId)
                .eq(VillageFloorEntity::getFloorNo, floorNo)
        );

        return CopyUtils.copyObj(entity, VillageFloorDto.class);
    }

    @Override
    public List<VillageFloorDto> selectByBuildingId(Long buildingId) {
        List<VillageFloorEntity> entityList = villageFloorDao.selectList(new LambdaQueryWrapper<VillageFloorEntity>()
                .eq(VillageFloorEntity::getBuildingId, buildingId)
        );
        return CopyUtils.copyList(entityList, VillageFloorDto.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void generateByBuildingsConfig(List<VillageFloorDto> floors) {
        for (VillageFloorDto floor : floors) {
            Long id = save(floor);

            if (floor.getVillageRoomDtoList() != null) {
                floor.getVillageRoomDtoList().forEach(v -> {
                    v.setFloorId(id);
                    villageRoomService.save(v);
                });
            }
        }
    }

    @Override
    public VillageFloorDto selectCacheById(Long id) {
        return CacheKit.cacheToRedis(
                () -> selectById(id),
                VILLAGE_FLOOR_CACHE_BY_ID + id,

                SystemConstants.NOT_NULL_CACHE_EXPIRE_SECONDS
        );
    }

    @Override
    public VillageFloorDto selectById(Long id) {
        VillageFloorEntity entity = villageFloorDao.selectById(id);
        return paddingField(CopyUtils.copyObj(entity, VillageFloorDto.class));
    }

    @Override
    public List<VillageFloorDto> queryList(Map<String, Object> params) {
        List<VillageFloorEntity> list = villageFloorDao.queryList(params);
        List<VillageFloorDto> result = CopyUtils.copyList(list, VillageFloorDto.class);
        result.forEach(this::paddingField);
        return result;
    }

    private VillageFloorDto paddingField(VillageFloorDto dto) {
        if (dto == null) {
            return null;
        }
        if (dto.getBuildingId() != null) {
            VillageBuildingDto villageBuildingDto = villageBuildingService.selectCacheById(dto.getBuildingId());
            if (villageBuildingDto != null) {
                dto.setVillageName(villageBuildingDto.getVillageName());
                dto.setBuildingName(villageBuildingDto.getName());
            }
        }
        return dto;
    }

    @Override
    public int queryTotal(Map<String, Object> params) {
        return villageFloorDao.queryTotal(params);
    }

    @Override
    public Long save(VillageFloorDto dto) {
        VillageFloorEntity entity = CopyUtils.copyObj(dto, VillageFloorEntity.class);
        entity.setId(Snowflake.nextId());
        villageFloorDao.insert(entity);
        return entity.getId();
    }

    @Override
    public void updateById(VillageFloorDto dto) {
        VillageFloorEntity entity = CopyUtils.copyObj(dto, VillageFloorEntity.class);
        villageFloorDao.updateById(entity);
        CacheKit.invalidRedisCache(VILLAGE_FLOOR_CACHE_BY_ID + dto.getId());
    }


    private static String getColumnName(String fieldName) {
        Field[] declaredFields = VillageFloorEntity.class.getDeclaredFields();
        for (Field declaredField : declaredFields) {
            declaredField.setAccessible(true);
            if (declaredField.getName().equals(fieldName)) {
                TableField annotation = declaredField.getAnnotation(TableField.class);
                if (annotation != null && StringUtils.isNotBlank(annotation.value())) {
                    return annotation.value();
                }
                return StrUtil.toUnderlineCase(declaredField.getName());
            }
        }
        return null;
    }


    @Override
    public void deleteById(Long id) {
        villageFloorDao.deleteById(id);
        CacheKit.invalidRedisCache(VILLAGE_FLOOR_CACHE_BY_ID + id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(Long[] ids) {
        for (Long id : ids) {
            deleteById(id);
        }
    }
}
